package com.itheima.behaviour.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.behaviour.dto.FollowBehaviorDto;
import com.itheima.behaviour.mapper.ApBehaviorEntryMapper;
import com.itheima.behaviour.mapper.ApFollowBehaviorMapper;
import com.itheima.behaviour.pojo.ApBehaviorEntry;
import com.itheima.behaviour.pojo.ApFollowBehavior;
import com.itheima.behaviour.service.ApFollowBehaviorService;
import com.itheima.common.constants.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @description <p>APP关注行为 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.behaviour.service.impl
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements ApFollowBehaviorService {

    @Autowired
    private ApBehaviorEntryMapper apBehaviorEntryMapper;

    /**
     * 同步app用户的关注行为
     * @param dto
     */
    @Override
    public void saveFollowBehavior(FollowBehaviorDto dto) {
        // 1.entry_id来源于ap_behavior_entry_id
        // 默认为用户类型
        Integer entryId = dto.getUserId();
        int type = SystemConstants.TYPE_USER; // type = 1 用户 0 匿名登录
        if (entryId == type) {
            // 设备id
            entryId = dto.getEquipmentId();
            // 用户类型
            type = SystemConstants.TYPE_E;
        }
        ApBehaviorEntry entry = apBehaviorEntryMapper.findByEntryIdAndType(entryId, type);

        // 2. 存入收据到ap_follow_behavior
        if(null != entry){
            // 如果实体不存在，则不处理
            // 否则构建pojo，并添加到表中
            ApFollowBehavior pojo = new ApFollowBehavior();
            pojo.setArticleId(dto.getArticleId());
            pojo.setEntryId(entry.getId());
            pojo.setFollowId(dto.getFollowId());
            pojo.setCreatedTime(LocalDateTime.now());
            save(pojo);
        }
    }
}
